#!/bin/bash

ts_name=$1

if [[ "x$ts_name" == "x" ]]; then
    echo "ts_name is required."
    exit -1
fi
url=$2
if [[ "x$url" == "x" ]]; then
    echo "url is required."
    exit -1
fi


prefix=`echo ${url%/*}`
filename=`echo ${url##*/}`
filename_length=`echo ${#filename}`
filemame_prefix_length=$(expr $filename_length - 6)
filemame_prefix=`echo ${filename:0:filemame_prefix_length}`
echo $prefix
echo $filename
echo $filemame_prefix
for i in {1..100};do
    num=`printf "%03d" $i`
    this_filename="$filemame_prefix$num.ts"
    echo $num;
    {
        #test ! -f $filemame_prefix$num.ts && wget $prefix/$filemame_prefix$num.ts
        test ! -f "$filemame_prefix$num.ts" && echo "$prefix/$filemame_prefix$num.ts"
        sleep 5
        test ! -f "$filemame_prefix$num.ts" && echo "$prefix/$filemame_prefix$num.ts" > "$filemame_prefix$num.ts"
    }&
    if [[ $i -lt 5 ]]; then
        continue
    fi
    waiting_file_num=$(expr $i - 5)
    waiting_file_name="$filemame_prefix`printf "%03d" $waiting_file_num`.ts"
    while [[ ! -f "$this_filename" ]];do
        echo "waiting for $this_filename"
        sleep 1
    done
done

# TODO un complete

